package com.example.nfc.barcodescan.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatDelegate;
import androidx.fragment.app.FragmentActivity;


import com.example.nfc.R;
import com.example.nfc.barcodescan.bean.ZxingConfig;
import com.example.nfc.barcodescan.camera.CameraManager;
import com.example.nfc.barcodescan.common.Constant;
import com.example.nfc.barcodescan.view.ViewfinderView;
import com.example.nfc.server.utils.CommonUtils;
import com.example.nfc.server.utils.DisplayUtil;
import com.example.nfc.server.utils.photo.ImageUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;



/**
 * @author: youdelu
 * @date: 2017/10/26 15:22
 * @declare :扫一扫
 */

public class CaptureActivity extends FragmentActivity implements SurfaceHolder.Callback, View.OnClickListener {

    private static final String TAG = CaptureActivity.class.getSimpleName();
    public ZxingConfig config;
    private SurfaceView previewView;
    private ViewfinderView viewfinderView;
    private ImageView mFlight,mBack;
    private TextView titleView;
    private boolean hasSurface;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private SurfaceHolder surfaceHolder;


    private TextView tips,result;



    private int selectPosition = 0 ;

    private String barcode = "";
    private int type = 0 ;//0安装 1 维修

    public static final int TYPE_INSTALL = 0 ;
    public static final int TYPE_REPAIR = 1 ;


    public static final String EXTRA_IMAGE_TITLE = "EXTRA_IMAGE_TITLE";
    public static final String EXTRA_IMAGE_POSITION = "EXTRA_IMAGE_POSITION";
    public static final String EXTRA_IMAGE_TYPE = "EXTRA_IMAGE_TYPE";

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }


    /**
     * 调试用的  输出当前条码照片 正式版注释
//     * @param data
//     * @param w
//     * @param h
     */

//    public void save(byte[] data,int w,int h){
//
//        Rect rect = new Rect(0,0,w,h);
//
//        BitmapFactory.Options newOpts = new BitmapFactory.Options();
//        newOpts.inJustDecodeBounds = true;
//        YuvImage yuvimage = new YuvImage(
//                data,
//                ImageFormat.NV21,
//                w,
//                h,
//                null);
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        yuvimage.compressToJpeg(rect, 80, baos);// 80--JPG图片的质量[0-100],100最高
//        byte[] rawImage = baos.toByteArray();
//
//        //将rawImage转换成bitmap
//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inPreferredConfig = Bitmap.Config.RGB_565;
//        Bitmap bitmap = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length, options);
//        String filepath = FileUtil.saveCodebarBitmap(mContext,bitmap);
//        NLog.e("dsfgsdfsdf",filepath);
//    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private TextView msg;

    static {
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 保持Activity处于唤醒状态
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.setStatusBarColor(Color.BLACK);
        }

        /*先获取配置信息*/
        try {
            config = (ZxingConfig) getIntent().getExtras().get(Constant.INTENT_ZXING_CONFIG);
        } catch (Exception e) {

            Log.i("config", e.toString());
        }

        if (config == null) {
            config = new ZxingConfig();
        }


        setContentView(R.layout.activity_capture);
        initView();

        hasSurface = false;

        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);
        beepManager.setPlayBeep(config.isPlayBeep());
        beepManager.setVibrate(config.isShake());

        CommonUtils.checkABICanSupport(CaptureActivity.this,"条码/二维码识别", new CommonUtils.CheckAPICanSupportBack() {
            @Override
            public void support() {
                isSupportScan = true;
            }
            @Override
            public void notSupport(){
                isSupportScan = false;
            }
        });

    }
    public static boolean isSupportScan = true;




    private LinearLayout  findView;
    private void initView() {
        findView = findViewById(R.id.findView);
        RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams)findView.getLayoutParams();
        layoutParams1.topMargin= DisplayUtil.dip2px(CaptureActivity.this,55);
        findView.setLayoutParams(layoutParams1);

        tips = findViewById(R.id.tips);
        result = findViewById(R.id.result);
        titleView = findViewById(R.id.title);
        mBack = findViewById(R.id.ic_back);
        msg = findViewById(R.id.msg);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        type = getIntent().getIntExtra(EXTRA_IMAGE_TYPE, 0);

            String title = getIntent().getStringExtra(EXTRA_IMAGE_TITLE);
            if(title!=null){
                titleView.setText(title);
                titleView.setVisibility(View.VISIBLE);
            }

        previewView = findViewById(R.id.preview_view);
        previewView.setOnClickListener(this);

        viewfinderView = findViewById(R.id.viewfinder_view);
        viewfinderView.setZxingConfig(config);


        mFlight = findViewById(R.id.flightBtn);
        mFlight.setOnClickListener(this);

        /*有闪光灯就显示手电筒按钮  否则不显示*/
        if (isSupportCameraLedFlash(getPackageManager())) {
            mFlight.setVisibility(View.VISIBLE);
        } else {
            mFlight.setVisibility(View.GONE);
        }
    }


    /**
     * @param pm
     * @return 是否有闪光灯
     */
    public static boolean isSupportCameraLedFlash(PackageManager pm) {
        if (pm != null) {
            FeatureInfo[] features = pm.getSystemAvailableFeatures();
            if (features != null) {
                for (FeatureInfo f : features) {
                    if (f != null && PackageManager.FEATURE_CAMERA_FLASH.equals(f.name)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * @param flashState 切换闪光灯图片
     */
    public void switchFlashImg(int flashState) {

        if (flashState == Constant.FLASH_OPEN) {
            mFlight.setImageResource(R.drawable.icon_flight_open);
        } else {
            mFlight.setImageResource(R.drawable.icon_flight_close);
        }

    }

    /**
     * 获取条码标题
     * @param position
     * @return
     */
    public String getTitle(int position){
        return "扫描条码";
    }

    /**
     * @param scanResult 返回的扫描结果
     */
    private boolean hasTips = false ;
    public void handleDecode(ScanResult scanResult) {

        inactivityTimer.onActivity();

        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) result.getLayoutParams();
        lp.topMargin =getFramingRect().top+(getFramingRect().bottom-getFramingRect().top)/2;
        result.setLayoutParams(lp);
        result.setText(scanResult.getResult().getText());

        if(!scanResult.getResult().getText().matches("^[A-Z0-9]+$")) {
            msg.setText("错误:条码只能包含大写字母和数字!");
            restart();
            return;
        }
            beepManager.playBeepSoundAndVibrate();

            Intent intent = getIntent();
            intent.putExtra(Constant.CODED_CONTENT,scanResult.getResult().getText());
            setResult(RESULT_OK, intent);
            finish();
    }

    //重新扫描
    public void restart(){
        Handler handler =  getHandler();
        if (handler != null) {
            Message message = Message.obtain(handler,
                    Constant.RESTART_PREVIEW);
            message.sendToTarget();
        }
    }



    @Override
    protected void onResume() {
        super.onResume();

        cameraManager = new CameraManager(getApplication(), config);

        viewfinderView.setCameraManager(cameraManager);
        handler = null;

        surfaceHolder = previewView.getHolder();
        if (hasSurface) {

            initCamera(surfaceHolder);
        } else {
            // 重置callback，等待surfaceCreated()来初始化camera
            surfaceHolder.addCallback(this);
        }

        beepManager.updatePrefs();
        inactivityTimer.onResume();

    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            // 打开Camera硬件设备
            cameraManager.openDriver(surfaceHolder);
            // 创建一个handler来打开预览，并抛出一个运行时异常
            if (handler == null) {
                handler = new CaptureActivityHandler(this, cameraManager);
            }

        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback() {
        public void onShutter() {
        }
    };



    @Override
    protected void onPause() {

        Log.i("CaptureActivity","onPause");
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();

        if (!hasSurface) {

            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        viewfinderView.stopAnimator();
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }


    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void onClick(View view) {

        int id = view.getId();
        if (id == R.id.flightBtn) {
            /*切换闪光灯*/
            cameraManager.switchFlashLight(handler);
        }

    }


    //获得取景框区域
    public Rect getFramingRect() {
        return cameraManager.getFramingRect();
    }
    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("格力条码扫描工具");
        builder.setMessage("相机被占用或没有权限，请检查");
        builder.setPositiveButton("确定", new FinishListener(this));
        builder.setOnCancelListener(new FinishListener(this));
        builder.show();
    }
}
